﻿using MD5Hash;
using MediatR;
using Microsoft.IdentityModel.Tokens;
using RBAC.ApiReads.Application.Command;
using RBAC.ApiReads.DTO;
using RBAC.Domain.RbacEntity;
using RBAC.Infrasturcture.Interfaces;
using RBAC.ResultCode;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace RBAC.ApiReads.Application.Commandhandler
{
    public class GetLoginCommandhandler : IRequestHandler<GetLoginCommand, ApiResult<UserDTO>>
    {
        private readonly IBaseRepository<User> userrepository;
        private readonly ILogger<GetLoginCommandhandler> logger;
        private readonly IBaseRepository<Role> rolebaseRepository;
        private readonly IBaseRepository<UserRole> userrolerepository;

        public GetLoginCommandhandler(IBaseRepository<User> userrepository,ILogger<GetLoginCommandhandler> logger,IBaseRepository<Role> rolebaseRepository,IBaseRepository<UserRole> userrolerepository)
        {
            this.userrepository = userrepository;
            this.logger = logger;
            this.rolebaseRepository = rolebaseRepository;
            this.userrolerepository = userrolerepository;
        }
        public async Task<ApiResult<UserDTO>> Handle(GetLoginCommand request, CancellationToken cancellationToken)
        {
            ApiResult<UserDTO> result = new ApiResult<UserDTO>();
            result.Code = ApiResultEnum.登录成功;
            result.Message = ApiResultEnum.登录成功.ToString();

            try
            {
                logger.LogInformation("日志信息");
                if (string.IsNullOrEmpty(request.UserName)) 
                {
                    throw new Exception("用户名不能为空");
                
                }
                if (string.IsNullOrEmpty(request.UserPwd))
                {
                    throw new Exception("密码不能为空");

                }
                //查询用户是否存在
                var info = userrepository.GetAll().FirstOrDefault(x => x.UserName == request.UserName);
               // request.UserPwd = request.UserPwd.GetMD5();
                if (info == null)
                {
                    throw new Exception("用户不存在");
                }
                //request.UserPwd = request.UserPwd.GetMD5();
                if (info.UserPwd == request.UserPwd.GetMD5())
                {
                    var list = from a in userrepository.GetAll()
                               join b in userrolerepository.GetAll()
                               on a.UserId equals b.UserId
                               join c in rolebaseRepository.GetAll()
                               on b.RoleId equals c.RoleId
                               where a.UserName==request.UserName
                               select new UserDTO
                               {
                                   UserId = a.UserId,
                                   UserName = a.UserName,
                      
                                   RoleName = c.RoleName
                               };
                    var entity = list.FirstOrDefault();
                    result.Data = entity;
                    result.Data.Token = CreateTokenString(result.Data);
                }
                else
                {
                    throw new Exception("密码错误");

                }




            }
            catch (Exception ex)
            {
             
                result.Code = ApiResultEnum.登录失败;
                result.Message = ApiResultEnum.登录失败.ToString();
            }

            return await Task.FromResult(result);
        }
        /// <summary>
        /// 生成 JWT Token（令牌）
        /// </summary>
        /// <returns>返回Token值</returns>
        private string CreateTokenString(UserDTO dto)
        {
            //私钥
            var secretByte = Encoding.UTF8.GetBytes("kdsfldsflkdslkflkdsflkdslfdslkflk");
            // 非对称加密
            var signingKey = new SymmetricSecurityKey(secretByte);
            // 使用256 生成数字签名
            var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);
            //用户信息
            Claim[] claims = new Claim[]
            {
               new Claim("UserId",dto.UserId.ToString()),
               new Claim("UserName",dto.UserName),


            };

            // 生成Token
            var token = new JwtSecurityToken(
                issuer: "BeiJingBW",
                audience: "BeiJingBW",
                expires: DateTime.Now.AddDays(1), // 一天后过期
                signingCredentials: signingCredentials,
                claims: claims
            );
            // 生成token 字符串
            var strToken = new JwtSecurityTokenHandler().WriteToken(token);
            return strToken;
        }
    }
}
